package result

import "encoding/json"

//统一返回体

var (
	// OK
	OK  = response(200, "ok") // 通用成功
	Err = response(500, "")   // 通用错误

	// 服务级错误码
	ErrParam     = response(10001, "参数有误")
	ErrSignParam = response(10002, "签名参数有误")
	ErrServer    = response(10003, "请求服务器异常")

	// 模块级错误码 - 用户模块
	ErrUserService  = response(20100, "用户服务异常")
	ErrUserPhone    = response(20101, "用户手机号不合法")
	ErrUserCaptcha  = response(20102, "用户验证码有误")
	ErrUserNotFound = response(20103, "用户名不存在")
	ErrPassErr      = response(20104, "用户密码错误")
	ErrReqErr       = response(20105, "请求参数有误")

	// 设备模块错误
	ErrDeviceNotFound = response(20106, "设备不存在")
	ErrStreamServer   = response(20107, "请求流媒体错误")
	ErrGB28181Server  = response(20108, "请求国标错误")
	ErrGB28181Play    = response(20109, "国标点播错误")
	ErrOnvif          = response(20110, "onvif请求错误")
	ErrZlmParam       = response(20111, "流媒体请求参数错误")
	// ......

	//级联新增
	ErrGBCascadeParam = response(20112, "新增级联错误")
	ErrDataNotFound   = response(20106, "设备不存在")

	ErrPtzCtl      = response(20106, "ptz控制错误")
	ErrPresetExist = response(20106, "预置点已存在")
)

type Response struct {
	Code int         `json:"code"` // 错误码
	Msg  string      `json:"msg"`  // 错误描述
	Data interface{} `json:"data"` // 返回数据
}

// 自定义响应信息
func (res *Response) WithMsg(message string) Response {
	return Response{
		Code: res.Code,
		Msg:  message,
		Data: res.Data,
	}
}

// 追加响应数据
func (res *Response) WithData(data interface{}) Response {
	return Response{
		Code: res.Code,
		Msg:  res.Msg,
		Data: data,
	}
}

// ToString 返回 JSON 格式的错误详情
func (res *Response) ToString() string {
	err := &struct {
		Code int         `json:"code"`
		Msg  string      `json:"msg"`
		Data interface{} `json:"data"`
	}{
		Code: res.Code,
		Msg:  res.Msg,
		Data: res.Data,
	}
	raw, _ := json.Marshal(err)
	return string(raw)
}

// 实现error
func (res *Response) Error() string {
	return res.Msg
}

// 构造函数
func response(code int, msg string) *Response {
	return &Response{
		Code: code,
		Msg:  msg,
		Data: nil,
	}
}
